package net.muchine.test.spring.data.tutorial.core;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import net.muchine.test.spring.data.tutorial.config.SpringMongoConfig;
import net.muchine.test.spring.data.tutorial.domain.Address;
import net.muchine.test.spring.data.tutorial.domain.User;

public class UserRepository {
	// For Annotation
	private ApplicationContext context = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
	private MongoOperations mongo = context.getBean(MongoTemplate.class);
			
	private void save(User user) {
		mongo.save(user, "users");
	}
	
	private void update() {
		mongo.updateMulti(new Query(Criteria.where("username").is("sejoon").and("password").is("welcome1")), 
				Update.update("password", "new password"), "users");
	}
	
	private void remove(String username) {
		mongo.remove(new Query(Criteria.where("username").is(username)), "users");
	}
	
	private User find(String username) {
		return mongo.findOne(new Query(Criteria.where("username").is(username)), User.class, "users");
	}
	
	private List<User> findAll() {
		return mongo.findAll(User.class, "users");
	}
	
	public static void main(String[] args) {
		UserRepository repository = new UserRepository();
		
		User user = new User("sejoon", "welcome1");
		user.setHomeAddress(new Address("KR", "Seoul", "Namdaemoon-ro"));
		
		// save
		repository.save(user);
		
		// find
		User found = repository.find(user.getUsername());
		System.out.println("found user: " + found);
		
		// update
		repository.update();
		found = repository.find(user.getUsername());
		System.out.println("updated user: " + found);
		
		// list
		List<User> users = repository.findAll();
		System.out.println(users);
		
		// save again
		user.setPassword("welcome2");
		repository.save(user);
		
		// delete
//		repository.remove(user.getUsername());
	}
}
